import DatePicker from "components/antd-compatible/date-picker";
/**
 * Created by tanbingqin on 2020/7/2.
 */
import React, { Component, PropTypes } from "react";
import { messages, uniqueArr, eventTrack } from 'share/common'
import { connect } from 'react-redux';
import moment from 'moment'
import requestService from 'containers/request/request.service'
import baseService from 'share/base.service'
import travelService from 'containers/request/travel-request/travel.service'
import errorMessage from 'share/errorMessage';
import 'styles/request/new-card-request.scss'
import { Button, Row, Col, Icon,  Checkbox, message, Popconfirm, Spin, Modal, Progress } from 'antd'
import Condition from 'components/condition';
const If = Condition.If;
import emptyImg from 'images/travel/empty.png';
import travelUtil from 'containers/request/travel-request/travelUtil'
import requestUtil from 'containers/request/slide/request-util'
import TravelLocation from 'containers/request/travel-request/comp/location'
const CheckboxGroup = Checkbox.Group;
import debounce from 'lodash.debounce'
import ItineraryList from 'containers/request/slide/content/itinerary-list'
import ItineraryBudget from 'containers/request/slide/content/itinerary-budget'
import ItinerarySubsidy from 'containers/request/slide/content/itinerary-subsidy'
import SlideFrame from 'components/slide-frame'
import Skeleton from 'components/skeleton';

class RequestItinerary extends Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      itineraryHeadList: [], //行程头列表
      isEdit: false, //是否是行程头编辑状态
      isEditList: false, //是否是行程头列表编辑状态
      quickExpenseTypeList: [], //可选的快捷规划费用类型
      tempHeadList: [], //行程头的一次增量添加
      subsidyLoading: false, //补贴计算按钮的loading
      subsidyConfig: {}, //从后台获取的差补配置，带行程头展示数据
      calculating: false, //差补明细生成进度的计算弹框
      percent: 0,
      roomNum: 0, //酒店套件的房间数量
    };
    this.handleNewTemp = debounce(this.handleNewTemp, 200);
  }

  componentDidMount() {
    this.getItineraryHead();
    this.initQuickExpenseType();
    this.initHotelRoom();
  }

  //isSubsidy是否要处理差补明细
  getItineraryHead = (isSubsidy) => {
    const { info } = this.context;
    const { refreshItinerary } = this.props;
    if (info.applicationOID) {
      this.setState({loading: true});
      requestService.getItineraryHead(info.applicationOID, true).then(res => {
        this.setState({itineraryHeadList: res.data});
        if (isSubsidy) {
          this.handleBatchSubsidyDetail();
        } else {
          this.setState({loading: false});
        }
        if (refreshItinerary) {
          refreshItinerary(res.data);
        }
      }).catch(err => {
        this.setState({loading: false});
        errorMessage(err.response);
      });
    }
  };

  initQuickExpenseType = () =>{
    const { form, jobInfo, info } = this.context;
    const { user } = this.props;
    if (form.formOID) {
      let companyOID = travelUtil.getFormHeadValue(info.custFormValues, 'select_company') || jobInfo.companyOID || user.companyOID;
      let params = {
        companyOID,
        formOID: form.formOID,
        subsidyType: 0,
        userOID: user.userOID,
        setOfBooksId: form.setOfBooksId
      };
      requestService.getQuickExpenseType(params).then(res => {
        this.setState({quickExpenseTypeList: res.data && res.data.rows});
      }).catch(err => {
        errorMessage(err.response);
      });
    }
  };

  //初始化酒店房间数量
  initHotelRoom = () => {
    const { info } = this.context;
    let outNum = travelUtil.getFormHeadValue(info.custFormValues, 'out_participant_num') || travelUtil.getFormHeadValue(info.custFormValues, 'out_participant_full_name');
    let select_participant = [];
    select_participant = travelUtil.getFormHeadValue(info.custFormValues, 'select_participant');
    travelService.getMaxRoom(outNum, select_participant).then(res => {
      this.setState({roomNum: res.data.maxRoomNumber});
    }).catch(err => {
      errorMessage(err.response);
    });
  };

  handleNewHead = () => {
    eventTrack({
      category: '行程新建',
      action: '新建行程'
    });
    const { itineraryHeadList } = this.state;
    this.setState({isEdit: true});
    let tempHeadList = [];
    let newHead = this.generateNewHead(itineraryHeadList);
    tempHeadList.push(newHead);
    this.setState({tempHeadList});
  };

  //生成一个行程头
  generateNewHead = (headList) => {
    const { info } = this.context;
    const { quickExpenseTypeList } = this.state;
    return {
      applicationOID: info.applicationOID,
      frontHeadID: travelUtil.generateUid(),
      fromCityName: requestUtil.processDefaultHeadCity(headList, 'toCityName', 'toCityCode').toCityName,
      fromCityCode: requestUtil.processDefaultHeadCity(headList, 'toCityName', 'toCityCode').toCityCode,
      toCityName: '',
      toCityCode: '',
      startDate: requestUtil.processDefaultHeadDate(info.custFormValues, headList, 'startDate'),
      endDate: requestUtil.processDefaultHeadDate(info.custFormValues, headList, 'endDate'),
      quickExpenseOIDList: (quickExpenseTypeList || []).map(item => item.expenseTypeOID)
    };
  };

  handleNewTemp = () => {
    eventTrack({
      category: '行程新建',
      action: '再加一程'
    });
    let { tempHeadList } = this.state;
    if (!requestUtil.validateHead(true, tempHeadList)) {
      return;
    }
    let newHead = this.generateNewHead(tempHeadList);
    tempHeadList.push(newHead);
    this.setState({tempHeadList});
  };

  handleChangeHeadValue = (value, index, key) => {
    if (key === 'quickExpenseOIDList') {
      eventTrack({
        category: '行程新建',
        action: '为您规划'
      });
    }
    if (key === 'fromCity') {
      eventTrack({
        category: '行程新建',
        action: '出发城市'
      });
    }
    if (key === 'toCity') {
      eventTrack({
        category: '行程新建',
        action: '到达城市'
      });
    }
    if (key === 'startDate') {
      eventTrack({
        category: '行程新建',
        action: '出发日期'
      });
    }
    if (key === 'endDate') {
      eventTrack({
        category: '行程新建',
        action: '离开日期'
      });
    }
    let { tempHeadList } = this.state;
    if (key === 'fromCity' || key === 'toCity') {
      tempHeadList[index][`${key}Name`] = value.adName;
      tempHeadList[index][`${key}Code`] = value.adCode;
    } else {
      tempHeadList[index][key] = value;
    }
    this.setState({tempHeadList});
  };

  handleDelete = (e, index) => {
    eventTrack({
      category: '行程新建',
      action: '删除'
    });
    let { tempHeadList } = this.state;
    tempHeadList.splice(index, 1);
    this.setState({tempHeadList});
  };

  handleCancelHead = () => {
    this.setState({tempHeadList: [], isEdit: false});
  };

  handleSaveHead = () => {
    let { tempHeadList } = this.state;
    const { info } = this.context;
    if (requestUtil.validateHead(false, tempHeadList)) {
      let params = requestUtil.processHeadParams(tempHeadList);
      this.setState({loading: true});
      requestService.addItineraryHead(info.applicationOID, params).then(res => {
        //如果有勾选了快捷规划，则直接打开明细添加的侧滑
        if (requestUtil.isSelectQuick(tempHeadList) && tempHeadList.length === res.data.length) {
          //把后台返回的行程头id塞到tempHeadList上
          tempHeadList && tempHeadList.forEach((tempHead, tempHeadIndex) => {
            tempHead.itineraryHeadId = res.data[tempHeadIndex].itineraryHeadId;
            tempHead.startDate = moment(tempHead.startDate).format('YYYY-MM-DD');
            tempHead.endDate = moment(tempHead.endDate).format('YYYY-MM-DD');
          });
          sessionStorage.setItem('isNeedApplicationRefresh', 'true');
          this.setState({tempHeadList, loading: false, isEdit: false}, this.handleOpenItinerary);
        } else {
          this.setState({tempHeadList: [], isEdit: false});
          this.getItineraryHead();
        }
      }).catch(err => {
        this.setState({loading: false});
        errorMessage(err.response);
      });
    }
  };

  handleChangeHead = (headList) => {
    this.setState({itineraryHeadList: headList});
  };

  handleOpenItinerary = () => {
    const { form, info, jobInfo } = this.context;
    const { tempHeadList, quickExpenseTypeList, roomNum } = this.state;
    let expenseTypeList = requestUtil.getAllSelectQuick(tempHeadList, quickExpenseTypeList); //选中的快捷规划费用类型的并集去重
    SlideFrame.open({
      title: messages('request-1.key271')/*行程明细*/,
      content: ItineraryBudget,
      afterClose: this.handleCloseSlide,
      params: {
        formInfo: form, //参数不能叫form，和antd的form就重名了
        info,
        jobInfo,
        expenseTypeList,
        itineraryHeadList: tempHeadList,
        roomNum,
        isQuickPlan: true
      }
    }, this);
  };

  handleAddBudget = (expense, itinerary) => {
    const { form, info, jobInfo } = this.context;
    const { roomNum } = this.state;
    itinerary.quickExpenseOIDList = [expense.expenseTypeOID];
    SlideFrame.open({
      title: messages('request-1.key271')/*行程明细*/,
      content: ItineraryBudget,
      afterClose: this.handleCloseSlide,
      params: {
        formInfo: form, //参数不能叫form，和antd的form就重名了
        info,
        jobInfo,
        expenseTypeList: [expense],
        itineraryHeadList: [itinerary],
        roomNum
      }
    }, this);
  };

  handleEditBudget = (applicationCustomBudgetId) => {
    eventTrack({
      category: '行程明细新建/编辑',
      action: '明细列表单行点击次数'
    });
    const { itineraryHeadList, roomNum } = this.state;
    const { form, info, jobInfo } = this.context;
    let expense = {};
    let headList = JSON.parse(JSON.stringify(itineraryHeadList));
    headList && headList.forEach(itinerary => {
      itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.forEach(budget => {
        if (budget.applicationCustomBudgetId === applicationCustomBudgetId) {
          expense.iconURL = budget.expenseTypeIconURL;
          expense.name = budget.expenseTypeName;
          expense.expenseTypeOID = budget.expenseTypeOID;
          itinerary.quickExpenseOIDList = [budget.expenseTypeOID];
        }
      });
    });
    SlideFrame.open({
      title: messages('request-1.key271')/*行程明细*/,
      content: ItineraryBudget,
      afterClose: this.handleCloseSlide,
      params: {
        formInfo: form, //参数不能叫form，和antd的form就重名了
        info,
        jobInfo,
        expenseTypeList: [expense],
        itineraryHeadList: headList,
        isEditBudget: true, //是否是编辑预算明细
        budgetId: applicationCustomBudgetId,
        roomNum
      }
    }, this);
  };

  handleCloseSlide = (success) => {
    const { refreshInfo } = this.context;
    if (success || sessionStorage.getItem('isNeedApplicationRefresh') === 'true') {
      refreshInfo();
      sessionStorage.setItem('isNeedApplicationRefresh', '');
    }
  };

  handleNewSubsidy = () => {
    eventTrack({
      category: '计算补贴',
      action: '计算补贴'
    });
    const { info } = this.context;
    this.setState({subsidyLoading: true});
    requestService.getSubsidyConfig(info.applicationOID).then(res => {
      this.setState({subsidyLoading: false, subsidyConfig: res.data}, this.handleAddSubsidy);
    }).catch(err => {
      errorMessage(err.response);
      this.setState({subsidyLoading: false});
    });
  };

  handleAddSubsidy = () => {
    const { form, info, jobInfo } = this.context;
    const { subsidyConfig } = this.state;
    SlideFrame.open({
      title: messages('request-1.key411')/*补贴计算*/,
      content: ItinerarySubsidy,
      afterClose: this.handleCloseSubsidySlide,
      params: {
        formInfo: form, //参数不能叫form，和antd的form就重名了
        info,
        jobInfo,
        subsidyConfig,
      }
    }, this);
  };

  //postData 生成差补明细所需要的数据
  handleCloseSubsidySlide = (postData) => {
    if (postData && postData.length) {
      this.setState({calculating: true, percent: 0}, this.percentPlus);
      requestService.calculateSubsidy(postData).then(res => {
        message.success(messages('request-1.key412')/*差补明细生成完成*/);
        this.setState({calculating: false}, () => {
          this.getItineraryHead(true);
        });
      }).catch(err => {
        this.state.calculating && errorMessage(err.response);
        this.setState({calculating: false});
      });
    }
  };

  //进度条数值控制器
  percentPlus = ()=> {
    let { percent } = this.state;
    if (percent <= 90) {
      percent += 9;
    }
    this.setState({percent}, () => {
      if(this.state.percent <= 99){
        setTimeout(this.percentPlus, 100);
      }
    });
  };

  //取消生成差补明细
  cancelCalculate = () => {
    const { info } = this.context;
    this.setState({calculating: false});
    requestService.stopCalculateSubsidy(info.applicationOID);
  };

  //处理批量差补明细的填写
  handleBatchSubsidyDetail = () => {
    const { form, info, jobInfo } = this.context;
    const { roomNum } = this.state;
    requestService.getItineraryHead(info.applicationOID, true, {filterItineraryTypes: 1006}).then(res => {
      this.setState({loading: false});
      let headList = [];
      res.data && res.data.forEach(itinerary => {
        if (itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.length) {
          headList.push(itinerary);
        }
      });
      if (!headList.length) {
        return;
      }
      let expenseTypeListTemp = [];
      headList.forEach(itinerary => {
        itinerary.quickExpenseOIDList = [];
        itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.forEach(budget => {
          let expense = {};
          expense.iconURL = budget.expenseTypeIconURL;
          expense.name = budget.expenseTypeName;
          expense.expenseTypeOID = budget.expenseTypeOID;
          expenseTypeListTemp.push(expense);
          itinerary.quickExpenseOIDList.push(budget.expenseTypeOID);
        });
        itinerary.quickExpenseOIDList = uniqueArr(itinerary.quickExpenseOIDList);
      });
      let expenseTypeList = requestUtil.getAllSelectQuick(headList, expenseTypeListTemp);
      sessionStorage.setItem('isNeedApplicationRefresh', 'true');
      SlideFrame.open({
        title: messages('request-1.key271')/*行程明细*/,
        content: ItineraryBudget,
        afterClose: this.handleCloseSlide,
        params: {
          formInfo: form, //参数不能叫form，和antd的form就重名了
          info,
          jobInfo,
          expenseTypeList: expenseTypeList,
          itineraryHeadList: headList,
          isEditBudget: true, //是否是编辑预算明细
          isBatchSubsidy: true, //是否批量处理差补明细
          roomNum
        }
      }, this);
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });
  };

  handleToggleListEdit = (value) => {
    this.setState({isEditList: value});
  };

  render() {
    const { itineraryHeadList, isEdit, quickExpenseTypeList, tempHeadList, loading, subsidyLoading, calculating,
      percent, isEditList } = this.state;
    const { info } = this.context;
    const { disabled, isCollapsed, isReadOnly } = this.props;
    return (
      <div className="itinerary-block">
        <Spin spinning={loading}>
          <If value={!disabled}>
            <Button type="primary" onClick={this.handleNewHead} style={{marginBottom: 12, marginRight: 12}} disabled={isEdit || isEditList}>{messages('request-1.key413')/*新建行程*/}</Button>
          </If>
          <If value={!disabled && itineraryHeadList.length}>
            <Button type="primary" onClick={this.handleNewSubsidy} style={{marginBottom: 12}} loading={subsidyLoading} disabled={isEdit || isEditList}>{messages('request-1.key414')/*计算补贴*/}</Button>
          </If>
          <If value={loading}>
            <Skeleton />
          </If>
          <If value={!itineraryHeadList.length && !isEdit && !loading}>
            <div style={{marginTop: 100, textAlign: 'center'}}>
              <div>
                <img src={emptyImg} style={{marginBottom: 18, width: 68, height: 68}} />
                <p style={{color: '#4E5B71'}}>{messages('request-1.key415')/*暂无行程，请先新建行程*/}</p>
              </div>
            </div>
          </If>
          <If value={isEdit}>
            <div className="new-itinerary-head">
              <div className="new-itinerary-head-title">
                <span className="title-font">{messages('request-1.key290')/*行程*/}</span>
              </div>
              <div className="new-itinerary-head-content">
                <Row type="flex" align="middle" gutter={16} className="list-header">
                  <Col span={9} offset={2}>
                    <Row type="flex" align="middle">
                      <Col span={11}>
                        {messages('request-1.key85')/*出发地*/}
                      </Col>
                      <Col span={11} offset={2}>
                        {messages('request-1.key395')/*目的地*/}
                      </Col>
                    </Row>
                  </Col>
                  <Col span={9}>
                    <Row type="flex" align="middle">
                      <Col span={11}>
                        {messages('request-1.key396')/*开始日期*/}
                      </Col>
                      <Col span={11} offset={2}>
                        {messages('request-1.key397')/*离开日期*/}
                      </Col>
                    </Row>
                  </Col>
                </Row>
                {tempHeadList.map((tempHead, index) => {
                  return (
                    <div key={tempHead.frontHeadID}>
                      <Row type="flex" align="middle" gutter={16} style={!!quickExpenseTypeList.length ? {marginBottom: 14} : {marginBottom: 20}}>
                        <Col span={2} style={{textAlign: 'right'}}>
                          <span className="content-no">{index + 1}</span>
                        </Col>
                        <Col span={9}>
                          <Row type="flex" align="middle">
                            <Col span={11}>
                              <TravelLocation
                                placeHolder={messages('request-1.key85')/*出发地*/}
                                value={{
                                  adCode: tempHead.fromCityCode,
                                  adName: tempHead.fromCityName
                                }}
                                onSelect={cityObj => this.handleChangeHeadValue(cityObj, index, 'fromCity')}
                              />
                            </Col>
                            <Col span={2} className="content-gap">—</Col>
                            <Col span={11}>
                              <TravelLocation
                                placeHolder={messages('request-1.key395')/*目的地*/}
                                value={{
                                  adCode: tempHead.toCityCode,
                                  adName: tempHead.toCityName
                                }}
                                onSelect={cityObj => this.handleChangeHeadValue(cityObj, index, 'toCity')}
                              />
                            </Col>
                          </Row>
                        </Col>
                        <Col span={9}>
                          <Row type="flex" align="middle">
                            <Col span={11}>
                              <DatePicker
                                placeholder={messages('request-1.key396')/*开始日期*/}
                                style={{width: '100%'}}
                                allowClear={false}
                                value={tempHead.startDate}
                                onChange={value => this.handleChangeHeadValue(value, index, 'startDate')}
                                disabledDate={c=> requestUtil.disabledDate(c, info && info.custFormValues)}
                              />
                            </Col>
                            <Col span={2} className="content-gap">—</Col>
                            <Col span={11}>
                              <DatePicker
                                placeholder={messages('request-1.key397')/*离开日期*/}
                                style={{width: '100%'}}
                                allowClear={false}
                                value={tempHead.endDate}
                                onChange={value => this.handleChangeHeadValue(value, index, 'endDate')}
                                disabledDate={c=> requestUtil.disabledDate(c, info && info.custFormValues)}
                              />
                            </Col>
                          </Row>
                        </Col>
                        <If value={tempHeadList.length > 1}>
                          <Col span={3}>
                          <span className="icon-btn">
                            <Popconfirm onConfirm={(e) => this.handleDelete(e, index)} title={messages('request-1.key386')/*你确认要删除？*/}>
                              <a onClick={(e) => {e.preventDefault();e.stopPropagation();}}><Icon type="delete" />&nbsp;{messages('common.delete')/*删除*/}</a>
                            </Popconfirm>
                          </span>
                          </Col>
                        </If>
                      </Row>
                      <If value={!!quickExpenseTypeList.length}>
                        <Row className="quick-expense-row">
                          <Col span={19} offset={2}>
                            <Row type="flex">
                              <div style={{flex: 'none'}}>
                                {messages('request-1.key416')/*已为您规划：*/}&nbsp;
                              </div>
                              <div style={{flex: 1}}>
                                <CheckboxGroup
                                  value={tempHead.quickExpenseOIDList}
                                  onChange={value => this.handleChangeHeadValue(value, index, 'quickExpenseOIDList')}>
                                  {quickExpenseTypeList.map(expense => {
                                    return (
                                      <Checkbox value={expense.expenseTypeOID}>{expense.name}</Checkbox>
                                    )
                                  })}
                                </CheckboxGroup>
                              </div>
                            </Row>
                          </Col>
                        </Row>
                      </If>
                    </div>
                  )
                })}
                <Row type="flex" align="middle" style={{marginBottom: 30}}>
                  <Col span={20} offset={2}>
                  <span className="icon-btn" onClick={this.handleNewTemp}>
                    <Icon type="plus" />&nbsp;
                    {messages('request-1.key417')/*再添加一程*/}
                  </span>
                  </Col>
                </Row>
                <Row type="flex" align="middle">
                  <Col span={20} offset={2}>
                    <Button type="primary" style={{marginRight: 8}} onClick={this.handleSaveHead}>{messages('common.save')/*保存*/}</Button>
                    <Button onClick={this.handleCancelHead}>{messages('common.cancel')/*取消*/}</Button>
                  </Col>
                </Row>
              </div>
            </div>
          </If>
          <If value={itineraryHeadList.length}>
            <ItineraryList
              itineraryHeadList={itineraryHeadList}
              onChange={this.handleChangeHead}
              onAddBudget={this.handleAddBudget}
              onEditBudget={this.handleEditBudget}
              onToggleEdit={this.handleToggleListEdit}
              disabled={disabled}
              isCollapsed={isCollapsed}
              disabledList={isEdit}
              isReadOnly={isReadOnly}
            />
          </If>
        </Spin>
        <Modal
          title={messages('request-1.key418')/*计算明细*/}
          maskClosable={false}
          closable={false}
          visible={calculating}
          footer={
            <div>
              <Button onClick={this.cancelCalculate}>{messages('common.cancel')/*取消*/}</Button>
            </div>
          }
        >
          <Progress percent={percent} status="active"/>
          <p>{messages('request-1.key419')/*正在生成差补明细...*/}</p>
        </Modal>
      </div>
    )
  }
}

RequestItinerary.propTypes = {
  disabled: PropTypes.bool, //是否是非编辑状态的差旅单，只能操作预订，目前没更改，所以没有停用行程
  isReadOnly: React.PropTypes.bool, //是否是只读状态，不展示预订按钮
  isCollapsed: PropTypes.bool,
  refreshItinerary: React.PropTypes.func, //告诉父组件行程数据
};

RequestItinerary.contextTypes = {
  applicant: PropTypes.object,
  form: PropTypes.object,
  info: PropTypes.object,
  jobInfo: PropTypes.object,
  refreshInfo: PropTypes.func,
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
  }
}

export default connect(mapStateToProps)(RequestItinerary)
